package com.hebtu.helper.modules.weather.controller;

import com.hebtu.helper.common.utils.H;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/weather")
@RestController
public class WeatherController {
    private final String target="https://restapi.amap.com/v3/weather/weatherInfo?city=130108&key=a0a7ae63aa6c47a724bf79791c0b074e";
    private Date lastRefresh=new Date();
    private Map<String,String> mp=new HashMap<>();
    private String result=null;
    @RequestMapping("/hebnu")
    public H getWeather(){
        if(new Date().getTime()-lastRefresh.getTime()<600*1000&&result!=null){
            return H.success().put("weather",result);
        }
        lastRefresh=new Date();
        try{
            String line;
            URL url=new URL(target);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while(null != (line=bReader.readLine()))
            {
                String[] lines=line.split(",");
                for (String s:lines){
                    String[] two= s.split(":");
                    if(two.length!=2)continue;
                    mp.put(two[0].substring(1,two[0].length()-1),two[1].substring(1,two[1].length()-1));
                }
            }
            bReader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            return H.error().put("data","查询失败，请检查接口");
        } catch (IOException e) {
            return H.error().put("data","查询失败，请检查接口");
        }

        try{
            result="今天天气："+mp.get("weather")+"，温度"+mp.get("temperature")+"，"+mp.get("winddirection")+
                    "风 "+ mp.get("windpower")+"级，湿度："+mp.get("humidity");
        }catch (Exception e){
            return H.error().put("data","查询失败，请检查信息");
        }
//        return H.success().put("weather",mp);
        return H.success().put("weather",result);
    }
}
